package configini

import (
	"fmt"
	"gitee.com/ichub/goconfig/common/base/basedto"
	"gitee.com/ichub/goconfig/common/base/baseutils"
	"gitee.com/ichub/goconfig/common/base/baseutils/fileutils"
	"github.com/sirupsen/logrus"
	"gopkg.in/ini.v1"
)

const general = "general"
const cms = "cms"

type IchubInicfg struct {
	basedto.BaseEntity
	ConfigFileName string
	funcDefineMap  map[string]string

	cfg *ini.File `json:"-"`
}

func NewIchubInicfg() *IchubInicfg {
	var iic = &IchubInicfg{}
	iic.InitProxy(iic)
	return iic
}

func (ichubConfigIni *IchubInicfg) Find2Map() map[string]string {

	var maps = ichubConfigIni.FindMap(general)
	var mapcms = ichubConfigIni.FindMap(cms)
	for k, v := range mapcms {
		maps["cms:"+k] = v
	}
	logrus.Debug(maps)
	return maps

}

func (ichubConfigIni *IchubInicfg) FindMap(domain string) map[string]string {
	var sec = ichubConfigIni.Find(domain)
	var funcmap = map[string]string{}

	for _, v := range sec.Keys() {
		funcmap[v.Name()] = v.Value()
	}
	ichubConfigIni.funcDefineMap = funcmap
	if len(sec.Keys()) != len(funcmap) {
		logrus.Error("func define有重复！")
	}
	return funcmap
}

// logrus.Debug(cfgIni.Find("general"))
func (ichubConfigIni *IchubInicfg) FindGeneral() *ini.Section {
	return ichubConfigIni.Find(general)
}
func (ichubConfigIni *IchubInicfg) FindCms() *ini.Section {
	return ichubConfigIni.Find(cms)
}
func (ichubConfigIni *IchubInicfg) Find(key string) *ini.Section {
	return ichubConfigIni.cfg.Section(key)

	//	Username:     cfg.Section("mysql").RuleKey("user").String(),
}
func (ichubConfigIni *IchubInicfg) Load(defFile string) error {
	// defFile = ichubcontext.CommonContext.DefineRuleFile
	ichubConfigIni.ConfigFileName = defFile
	if !ichubConfigIni.CheckFileExist(defFile) {
		return basedto.NewIchubError(500, "文件不存在！"+defFile)
	}
	cfg, err := baseutils.LoadIniCfg(defFile)

	if err != nil {
		fmt.Println(err)
		return err
	}
	fmt.Println(cfg)

	ichubConfigIni.cfg = cfg
	return nil
}
func (ichubConfigIni *IchubInicfg) CheckFileExist(filename string) bool {

	return fileutils.CheckFileExist(filename)

}
